<?php
/**
 * Create by 11li
 * Date 2020/3/6
 * Time 11:35
 *
 */

namespace app\api\controller;


use app\common\library\MyWeixin;
use app\common\model\Order;
use app\common\service\OrderService;
use app\common\service\StatusService;
use think\Db;
use think\Exception;

class Task
{
	/**
	 * 取消两小时前的订单
	 */
	public function cancelOrder()
	{
		$res = (new Order())
			->save(
				[
					'status' => StatusService::ORDER_CLOSE,
					'close_type' => StatusService::CLOSE_TIME
				]
				, [
				'create_time' => ['lt', strtotime('-2 hours')],
				'status' => StatusService::ORDER_WAIT_PAY
			]);
		echo date('Y-m-d H:i:s') . '订单取消结果:' . $res . PHP_EOL;
		
	}
	
	/**
	 * 签收7天前的订单
	 */
	public function signTimeOrder()
	{
		$str = date('Y-m-d H:i:s');
		
		$rows = $res = Db::name('order')
			->where([
				'create_time' => ['lt', strtotime('-7 days')],
				'status' => StatusService::ORDER_WAIT_SIGN
			])
			->select();
		
		if ($rows) {
			$obj = new OrderService();
			foreach ($rows as $row) {
				$res = $obj->signOrder($row['id'], $row['user_id']);
				$str .= $row['id'] . ':' . $res . PHP_EOL;
			}
		} else {
			$str .= '没有待签收订单';
		}
		
		echo $str .= PHP_EOL;
	}
	
	/**
	 * 关闭预约订单
	 */
	public function closeReservationOrder()
	{
		$str = date('Y-m-d H:i:s');
		//查找进行中和会尾款中的订单
		$records = Db::name('reservation')
			->where([
				'expire_time' => ['lt', time()],
				'status' => ['in', [StatusService::RESERVATION_WAIT_PAY, StatusService::RESERVATION_ING]]
			])
			->select();
		
		//付订金的退订金
		if ($records) {
			echo $str .= '没有要关闭的预约订单';
			die;
		}
		
		$weixin = MyWeixin::getInstance();
		try {
			//付尾款的退订金和尾款
			foreach ($records as $item) {
				//进行中的全部退尾款
				if ($item['status'] == StatusService::RESERVATION_ING) {
					$res = Db::name('order')
						->where(['record_id' => $item['id'], 'status' => StatusService::ORDER_RESERVATION_ING])
						->update([
							'status' => StatusService::ORDER_CLOSE,
							'update_time' => time(),
							'pay_status' => StatusService::ORDER_PAYMENT_REFUND_ING,
							'deposit_status' => StatusService::DEPOSIT_STATUS_REFUND_ING
						]);
					if(!$res) {
						throw new Exception($item['id'].'进行中的全部退尾款出错');
					}
				} else {
					//付尾款的检测付款人数
					$activity = Db::name('activityReservation')->find($item['activity_id']);
					if ($item['pay_number'] >= $activity['pay_number']) {
						//付尾款人数够，更改付尾款的人的订单状态为待发货
						$res = Db::name('order')
							->where(['record_id' => $item['id'], 'status' => StatusService::ORDER_WAIT_LAST_OTHER])
							->update([
								'status' => StatusService::ORDER_WAIT_SHIP,
								'update_time' => time()
							]);
						if(!$res) {
							throw new Exception($item['id'].'付尾款人数够，更改付尾款的人的订单状态为待发货出错');
						}
						//没付尾款的更改订单为关闭
						$res = Db::name('order')
							->where(['record_id' => $item['id'], 'status' => StatusService::ORDER_WAIT_LAST])
							->update([
								'status' => StatusService::ORDER_CLOSE,
								'update_time' => time()
							]);
						if($res === false) {
							throw new Exception($item['id'].'没付尾款的更改订单为关闭出错');
						}
					} else {
						$res = Db::name('order')
							->where([
								'record_id' => $item['id'],
								'status' => [
									'in',
									[StatusService::ORDER_WAIT_LAST, StatusService::ORDER_WAIT_LAST_OTHER]
								]
							])
							->update([
								'status' => StatusService::ORDER_CLOSE,
								'update_time' => time(),
								'deposit_status' => StatusService::DEPOSIT_STATUS_REFUND_ING,
								'pay_status' => StatusService::ORDER_PAYMENT_REFUND_ING
							]);
						if(!$res) {
							throw new Exception($item['id'].'付尾款人数不足更改状态出错');
						}
					}
				}
				
				$refundList = Db::name('order')->alias('o')
					->join('user u', 'o.user_id = u.id', 'left')
					->where(['o.pay_status' => StatusService::ORDER_PAYMENT_REFUND_ING])
					->whereOr(['o.deposit_status' => StatusService::DEPOSIT_STATUS_REFUND_ING])
					->field('o.id, o.pay_amount, o.deposit_amount, o.pay_status, o.deposit_status, u.smallapp_openid,
					o.transaction_no, o.deposite_transaction_no')
					->select();
				if(!$refundList) {
					throw new Exception($item['id'].'没有要退款的记录');
				}
				
				foreach ($refundList as $order) {
					if($order['deposit_status'] == StatusService::DEPOSIT_STATUS_REFUND_ING) {
						$weixin->refund($order['deposite_transaction_no'], $order['id'].'_deposit_'.time(), $order['deposit_amount'], $order['deposit_amount'], '预约订单退款');
					}
					
					if($order['deposit_status'] == StatusService::ORDER_PAYMENT_REFUND_ING) {
						$amount = $order['pay_amount']-$order['deposit_amount'];
						$weixin->refund($order['transaction_no'], $order['id'].'_order_'.time(), $amount, $amount, '预约订单退款');
					}
				}
			}
			

		} catch (Exception $e) {
		
		}
	}
}